<template>
  <div style="width: 100%; height: 600px">
    <div id="container-b"></div>
  </div>
</template>
<script>
import { Graph, treeToGraphData } from "@antv/g6";
export default {
  mounted() {
    // 使用示例：生成一个深度为2，宽度为3的树
    const treeData = this.generateTreeData(3, 8);
    console.log(treeData, "treeData");
    const graph = new Graph({
      container: document.getElementById("container-b"),
      autoFit: "view",
      autoResize: true,
      padding: 20,
      data: treeToGraphData(treeData),
      node: {
        type: "html",
        style: (data) => {
          const size = [100, 20];
          const byteLength = this.getBytes(data.name);
          size[0] = byteLength * 8;
          return {
            size,
            // labelText: (d) => d.id,
            // labelPlacement: "right",
            // labelOffsetX: 5,
            innerHTML: `<div style="width: 100%; height: 100%; background: #7863FF; display: flex; justify-content: center; align-items: center;">  <span style="color: #fff; font-size: 12px;">${data.name}</span></div>`,
            // labelBackground: true,
            ports: [{ placement: "right" }, { placement: "left" }],
          };
        },
        animation: {
          enter: false,
        },
      },
      edge: {
        type: "cubic-horizontal",
        animation: {
          enter: false,
        },
      },
      layout: {
        type: "mindmap",
        direction: "LR",
        getHeight: () => 20,
        getWidth: () => 32,
        getVGap: () => 4,
        getHGap: () => 100,
      },
      behaviors: ["collapse-expand", "drag-canvas", "zoom-canvas"],
    });

    graph.render();
  },
  methods: {
    getBytes(params) {
      let bytes = params.length;
      for (let i = 0; i < bytes; i++) if (params.charCodeAt(i) > 255) bytes++;
      return bytes;
    },
    generateTreeData(depth, width) {
      function generateNode(id, depth) {
        if (depth === 0) {
          return { id: id, name: `Node ${id}`, children: [] };
        }
        const children = [];
        for (let i = 0; i < width; i++) {
          children.push(generateNode(id + "-" + i, depth - 1));
        }
        return { id: id, name: `Node ${id}`, children: children };
      }

      const rootId = "root";
      const data = generateNode(rootId, depth);
      return data;
    },
  },
};
</script>
<style scoped></style>
